package com.itboye.ihomebank.activity.home;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.activity.me.ChooseAreaActivity;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.EditBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.custom.XGridView;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.ImageCompress;
import com.itboye.ihomebank.util.LoadingDialogTwo;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.XImageLoader;
import com.itboye.ihomebank.widget.photo.Bimp;
import com.itboye.ihomebank.widget.photo.CopyOfPhotoActivity;
import com.itboye.ihomebank.widget.photo.CopyOfTestPicActivity;
import com.lzy.okgo.OkGo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * 发布房源（1）
 */
public class ActivityFaBuHouse extends BaseOtherActivity {
    View v_statusbar;
    TextView fabu_house_v;
    ImageView fabu_house_close;
    private ImageView fabu_house_img;// 大图
    private LinearLayout fabu_house_imgs;
    private ImageView fabu_house_add;// 添加图片
    private TextView fabu_house_ok;// 下一步
    private TextView fabu_house_fangshi;
    private EditText fabu_house_title, fabu_house_phone, fabu_house_people;

    private XGridView noScrollgridview;
    private GridAdapter adapter;

    RelativeLayout re_choose_city;// 选择市区
    TextView tv_city;

    List<String> list = new ArrayList<String>();

    /**
     * 小区的code
     */
    private String xiaoquCode;

    private String uid;
    protected StringBuffer imgBuffer = new StringBuffer();
    Intent intent;
    public static ActivityFaBuHouse context;

    LoadingDialogTwo loadingDialogTwo;

    //显示ImageView
    public static ImageView imgv;
    public static ActivityFaBuHouse getInstance() {
        return context;
    }

    private int pxW;//屏幕宽
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.fabu_house_close:
                finish();
                break;
            case R.id.fabu_house_ok:
                if (xiaoQuArea.equals("")||fabu_house_title.getText().toString().equals("")||listImg.size()<=0){
                    ByAlert.alert("请完善信息");
                    return;
                }
                imgBuffer = new StringBuffer();
                // {"code":-1,"data":"该类型图片需要比例4:3","notify_id":1478567658}
                uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
                List<File> files = new ArrayList<>();
                List<String> li = new ArrayList<>();
                for (String s : listImg) {
                    li.add(ImageCompress.compress(s));
                }
                listImg.clear();
                listImg.addAll(li);

                String title = fabu_house_title.getText().toString();
                String phone = fabu_house_phone.getText().toString();
                String people = fabu_house_people.getText().toString();

                intent = new Intent(ActivityFaBuHouse.this, ActivityFaBuHouseTwo.class);
                intent.putExtra("list", (Serializable) (listImg));
                intent.putExtra("title", title);
                intent.putExtra("imgIds", imgBuffer.toString());
                intent.putExtra("xiaoquCode", xiaoquCode);
                intent.putExtra("phone", phone);
//                intent.putExtra("people","真名");
                intent.putExtra("people", SPUtils.get(this, null, SPContants.RealName,"") + "");
                intent.putExtra("address", SPUtils.get(ActivityFaBuHouse.this, null, SPContants.SELECT_CITY, "") + "" + SPUtils.get(ActivityFaBuHouse.this, null, SPContants.SELECT_AREA, "") + "" + xiaoQuArea);
                intent.putExtra("detail", SPUtils.get(ActivityFaBuHouse.this, null, SPContants.SELECT_CITY, "") + xiaoQuArea);
                startActivity(intent);
                break;
            case R.id.re_choose_city:// 选择市区
                intent = new Intent(this, ChooseAreaActivity.class);
                startActivityForResult(intent, 101);
                break;
            default:
                break;
        }
    }

    public void guanbi() {
        finish();
    }


    @Override
    protected int layout_id() {
        return R.layout.activity_fabu_house;
    }

    @Override
    protected void onInitController() {
        Bimp.drr.clear();
        uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";

        fabu_house_phone.setEnabled(false);
        fabu_house_phone.setText(SPUtils.get(this, null, SPContants.MOBILE, "")
                + "");
        String sex = "";
        if ((SPUtils.get(this, null, SPContants.SEX, "") + "").equals("0")) {// 保密
            int length = (SPUtils.get(this, null, SPContants.RealName, "") + "")
                    .length();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < length - 1; i++) {
                sex += "*";
            }

        } else if ((SPUtils.get(this, null, SPContants.SEX, "") + "")
                .equals("1")) {//
            sex = "女士";
        } else if ((SPUtils.get(this, null, SPContants.SEX, "") + "")
                .equals("2")) {
            sex = "先生";
        }
        fabu_house_people.setEnabled(false);
        String name = SPUtils.get(this, null, SPContants.RealName,
                "") + "";
        if (name != "") {
            fabu_house_people.setText(name.charAt(0) + sex);
        }else {
            fabu_house_people.setText("无");
        }

        noScrollgridview = (XGridView) findViewById(R.id.noScrollgridview);
        noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        adapter = new GridAdapter(this);
        noScrollgridview.setAdapter(adapter);

        noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                if (arg2 == listImg.size()) {
                    new PopupWindows(ActivityFaBuHouse.this, noScrollgridview);
                } else {
                    Intent intent = new Intent(ActivityFaBuHouse.this,
                            CopyOfPhotoActivity.class);
                    intent.putExtra("ID", arg2);
                    intent.putExtra("type", 1);
                    startActivityForResult(intent, 101);
                }
            }
        });
        noScrollgridview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if(position==listImg.size()){
                    return false;
                }
                listImg.add(0, listImg.get(position));
                listImg.remove(position+1);

                //显示前剪切

                XImageLoader.load("file://" + listImg.get(0), fabu_house_img);
//                imgv=fabu_house_img;
//                startPhotoZoom(Uri.parse("file://" + listImg.get(0)), fabu_house_img);
                adapter.notifyDataSetChanged();
                return true;
            }
        });
        fabu_house_title.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (fabu_house_title.getLineCount()>1) {
                    fabu_house_title.setGravity(Gravity.LEFT);
                }else {
                    fabu_house_title.setGravity(Gravity.RIGHT);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);
        context = this;
        fabu_house_v.setVisibility(View.GONE);
        loadingDialogTwo = new LoadingDialogTwo(this);

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    private static final int TAKE_PICTURE_FANG_YUAN = 001;
    private String path = "";
    private String xiaoQuArea="";
    private EditBean editBean;
    public static List<String> listImg = new ArrayList<String>();

    String file_path;
    public void photo() {
//        String state = Environment.getExternalStorageState();
        file_path=Environment.getExternalStorageDirectory()+"/temp/"+System.currentTimeMillis() + ".jpg";

        File file=new File(file_path);
        if (!file.getParentFile().exists())file.getParentFile().mkdirs();
//        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //Android7.0以上URI
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            {

                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                //通过FileProvider创建一个content类型的Uri
                Uri uri = FileProvider.getUriForFile(this, "com.itboye.zhujia.fileprovider", file);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            } else
            {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
            }
            try
            {
                startActivityForResult(intent,
                        TAKE_PICTURE_FANG_YUAN);
            } catch (ActivityNotFoundException anf) {
                ByAlert.alert("摄像头尚未准备好");
            }

//        } else {
//            ByAlert.alert("请确认已经插入SD卡");
//        }
    }
    private String picture_name;
    private String fileName;

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE_FANG_YUAN:
                if (listImg.size() < 9 && resultCode == -1) {
                    //ImageCompress.compress(path);
                    //listImg.add(ImageCompress.compress(path));

//                    final Bitmap photo = data.getParcelableExtra("data");
                    Bitmap photo = BitmapFactory.decodeFile(file_path);
                    if(photo!=null){
                        doCropPhoto(new File(file_path));
                    }
                }
                break;

            case 400: //剪切后展示
//                String sdStatus = Environment.getExternalStorageState();
//                if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
//                    Log.i("TestFile",
//                            "SD card is not avaiable/writeable right now.");
//                    return;
//                }
                picture_name = android.text.format.DateFormat.format(
                        "yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
                        + ".jpg";
//                Bundle bundle = data.getExtras();
//                Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式

                Bitmap bitmap = BitmapFactory.decodeFile(outputUri.getPath());

                if (bitmap!=null){
                    // SavePicInLocal(bitmap);
                    FileOutputStream b = null;
                    File file = new File("/sdcard/Image/");
                    file.mkdirs();// 创建文件夹
                    fileName = "/sdcard/Image/" + picture_name;

                    try {
                        b = new FileOutputStream(fileName);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            b.flush();
                            b.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    listImg.add(fileName);
                }
                break;
        }
        if (requestCode == 101 && resultCode == 102) {
            fabu_house_img.setImageResource(R.drawable.wutu);
        }
        if (requestCode == 101 && resultCode == 103) {
//			fabu_house_img.setImageBitmap(Bimp.bmp.get(Bimp.bmp.size() - 1));
        }
        if (requestCode == 101 && resultCode == 104) {
            if (data != null) {
                xiaoquCode = data.getStringExtra("xiaoqu");
                xiaoQuArea = data.getStringExtra("xiaoquName");
                tv_city.setText(xiaoQuArea);
            }
        }
    }
    protected void onRestart() {
        adapter = new GridAdapter(this);
        noScrollgridview.setAdapter(adapter);
        if (listImg.size() > 0) {
            //显示前剪切

          //  XImageLoader.load("file://" + listImg.get(listImg.size() - 1), fabu_house_img);
            XImageLoader.load("file://" + listImg.get(0), fabu_house_img);
//            imgv=fabu_house_img;
//            startPhotoZoom(Uri.parse("file://" + listImg.get(0)), fabu_house_img);

        } else {
            fabu_house_img.setImageResource(R.drawable.wutu);
        }

        super.onRestart();
    }

    String crop_path;
    Uri outputUri;
    protected void doCropPhoto(File data){
        Intent intent = getCropImageIntent(data);
        startActivityForResult(intent, 400);
    }
    public  Intent getCropImageIntent(File data) {
        Intent intent = new Intent("com.android.camera.action.CROP");
//        intent.setClassName("com.android.camera", "com.android.camera.CropImage");
        crop_path=Environment.getExternalStorageDirectory()+"/crop/"+System.currentTimeMillis() + ".jpg";
        File file=new File(file_path);
        if (!file.getParentFile().exists())file.getParentFile().mkdirs();

        Uri imageUri;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        {

            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //通过FileProvider创建一个content类型的Uri
            imageUri = FileProvider.getUriForFile(ActivityFaBuHouse.this, "com.itboye.zhujia.fileprovider", data);
            outputUri=Uri.fromFile(file);
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        } else
        {
            imageUri =Uri.fromFile(data);
            outputUri =Uri.fromFile(file);
        }
//        intent.setType("image/*");
//        intent.putExtra("data", data);

        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 4);
        intent.putExtra("aspectY", 3);
//        intent.putExtra("outputX", pxW);// 输出图片大小
//        intent.putExtra("outputY", 0.75*pxW);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent .putExtra("scale", true);//黑边
        intent .putExtra("scaleUpIfNeeded", true);//黑边
//        intent.putExtra("return-data", true);
        return intent;
    }
//   //剪切图片
//    private void startPhotoZoom(Uri uri,ImageView ho) {
//        Intent intent = new Intent("com.android.camera.action.CROP");
//        intent.setDataAndType(uri, "image/*");
//        // crop为true是设置在开启的intent中设置显示的view可以剪裁
//        intent.putExtra("crop", "true");
//        // aspectX aspectY 是宽高的比例
//        intent.putExtra("aspectX", 4);
//        intent.putExtra("aspectY", 3);
//
//        // outputX,outputY 是剪裁图片的宽高
//        intent.putExtra("outputFormat", "JPEG");
//        intent.putExtra("noFaceDetection", true);
//        intent.putExtra("return-data", true);
//        startActivityForResult(intent, 400);
//    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        listImg.clear();
        OkGo.getInstance().cancelTag(this);
    }

    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater; // 视图容器
        private int selectedPosition = -1;// 选中的位置
        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public int getCount() {
            return (listImg.size() + 1);
        }

        public Object getItem(int arg0) {

            return null;
        }

        public long getItemId(int arg0) {

            return 0;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        /**
         * ListView Item设置
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            final int coord = position;
            ViewHolder holder = null;
            if (convertView == null) {

                convertView = inflater.inflate(R.layout.item_published_grida,
                        parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (position == listImg.size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(
                        getResources(), R.drawable.icon_addpic_unfocused));
                if (position == 9) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {

                XImageLoader.load("file://" + listImg.get(position),
                        holder.image);
//                imgv=holder.image;
//                startPhotoZoom(Uri.parse("file://" + listImg.get(position)), holder.image);
            }

            return convertView;
        }

        public class ViewHolder {
            public ImageView image;
        }
    }
    public class PopupWindows extends PopupWindow {

        public PopupWindows(Context mContext, View parent) {

            View view = View
                    .inflate(mContext, R.layout.item_popupwindows, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.fade_ins));
            LinearLayout ll_popup = (LinearLayout) view
                    .findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.push_bottom_in_2));

            setWidth(ViewGroup.LayoutParams.FILL_PARENT);
            setHeight(ViewGroup.LayoutParams.FILL_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();

            Button bt1 = (Button) view
                    .findViewById(R.id.item_popupwindows_camera);
            Button bt2 = (Button) view
                    .findViewById(R.id.item_popupwindows_Photo);
            Button bt3 = (Button) view
                    .findViewById(R.id.item_popupwindows_cancel);
            bt1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    photo();
                    dismiss();
                }
            });
            bt2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(ActivityFaBuHouse.this,
                            CopyOfTestPicActivity.class);
                    intent.putExtra("type", 4);
                    intent.putExtra("max", 9 - listImg.size());
                    startActivity(intent);
                    dismiss();
                }
            });
            bt3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });

        }
    }

}
